import {Modal, Form, Input, Upload, Button, Select, message} from 'antd'
import React, { useEffect, useState } from "react";

import { apiInterceptors, getSpaceList, getApplicationDetail, updateApplication, createApp, getRole, getTenantList } from '@/client/api';
import {nameRule} from "../../../utils/validationRules";

const RoleModal = ({ handleType, isModalOpen, setModal, appId, successCall, tenantId }: any) => {
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 14 },
    },
  };
  const [userForm] = Form.useForm();
  const [options, setOptions] = useState([])
  const [tenantOptions, setTenantOptions] = useState([])
  const [roleOptions, setRoleOptions] = useState([])
  const [roleInfo, setRoleInfo] = useState({})

  const filterOption = (input: string, option: { label: string; value: string }) => option?.label.includes(input)

  const submitHandle = async () => {
    try {
      const values = await userForm.validateFields();

      if (handleType === 'edit') {
        values.id = appId
        const [err] = await apiInterceptors(updateApplication({...roleInfo,...values}))
        if (!err) {
          message.success('操作成功')
        } else {
          return
        }
      }
      if (handleType === 'add') {
        const [err] = await apiInterceptors(createApp(values))
        if (!err) {
          message.success('操作成功')
        } else {
          return
        }
      }
      setModal(false)
      resetForm()
      successCall()
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  const cancelHandle = () => {
    setModal(false)
    resetForm()
  }
  const resetForm = () => {
    userForm.resetFields()
  }
  const getApplicationInfo = async () => {
    const [_, result] = await apiInterceptors(getApplicationDetail(appId))
    setRoleInfo(result)
    // result.knowledge_ids = result.knowledges.map((item:string) => Number(item))
    userForm.setFieldsValue(result)
  }
  const getKnowledgeList = async () => {
    const [_, result] = await apiInterceptors(getSpaceList({ tenant_id: tenantId, app_id: appId }))
    const optionList = result?.map((item: any) => ({
      label: item.name,
      value: item.id
    }))
    setOptions(optionList)
  }
  const getAllTenantList = async () => {
    const [_, result] = await apiInterceptors(getTenantList({page_num: 1, page_size: 9999}))
    const optionList = result.data.map((item: any) => ({
      label: item.name,
      value: item.id
    }))
    setTenantOptions(optionList)
  }
  const getAllRoleList = async () => {
    const [_, result] = await apiInterceptors(getRole({page_num: 1, page_size: 9999}))
    const optionList = result.data.map((item: any) => ({
      label: item.name,
      value: item.id
    }))
    setRoleOptions(optionList)
  }
  useEffect(() => {
    if (handleType === 'edit') {
      getApplicationInfo()
    }
    // getKnowledgeList()
    getAllTenantList()
    getAllRoleList()
  }, [])
  return (<>
    <Modal
      title={handleType === 'add' ? '新增应用' : '修改应用'}
      open={isModalOpen}
      onOk={submitHandle} onCancel={cancelHandle}
      width={600}
    >
      <Form {...formItemLayout} form={userForm}>
        <Form.Item
          label="应用名称" name="name"
          rules={[
            { required: true, message: '请输入应用名称' },
            nameRule
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="所属租户" name="tenant_id"
          rules={[
            { required: true, message: '请选择所属租户' },
          ]}
        >
          <Select
            allowClear
            filterOption={filterOption}
            placeholder="请选择所属租户"
            options={tenantOptions}
          />
        </Form.Item>
        {/*<Form.Item*/}
        {/*  label="关联知识库" name="knowledge_ids"*/}
        {/*  rules={[*/}
        {/*    { required: true, message: '请选择知识库' },*/}
        {/*  ]}*/}
        {/*>*/}
        {/*  <Select*/}
        {/*    mode="multiple"*/}
        {/*    allowClear*/}
        {/*    filterOption={filterOption}*/}
        {/*    placeholder="请选择关联知识库"*/}
        {/*    options={options}*/}
        {/*  />*/}
        {/*</Form.Item>*/}
        <Form.Item
          label="关联角色" name="role_ids"
        >
          <Select
            mode="multiple"
            allowClear
            filterOption={filterOption}
            placeholder="请选择关联角色"
            options={roleOptions}
          />
        </Form.Item>
        <Form.Item label="状态" name="status" rules={[{ required: true, message: '请选择状态' }]}>
          <Select
            placeholder="请选择状态"
            options={[
              { value: '1', label: '启用' },
              { value: '0', label: '禁用' },
            ]}
          />
        </Form.Item>
        <Form.Item label="描述" name="desc">
          <Input.TextArea style={{resize: 'none'}} rows={3}/>
        </Form.Item>
      </Form>
    </Modal>
  </>)
}

export default RoleModal
